package com.example.usbhidtool.tcp;


import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;

import com.easysocket.EasySocket;
import com.easysocket.config.DefaultMessageProtocol;
import com.easysocket.config.EasySocketOptions;
import com.easysocket.connection.heartbeat.HeartManager;
import com.easysocket.entity.OriginReadData;
import com.easysocket.entity.SocketAddress;
import com.example.usbhidtool.utils.JsonUtils;
import com.example.usbhidtool.utils.TimeUtil;

import java.util.Base64;
import java.util.Date;

public class SocketManager {

    public static final String TAG = "SOCKET";


    /**
     * @param context
     * @param socketAddress 服务器地址
     * @param port          端口号
     */
    public static void createConnection(Context context, String socketAddress, int port) {
        // socket配置
        EasySocketOptions options = new EasySocketOptions.Builder()
                .setCallbackIDFactory(new CallbackIDFactoryImpl())
                .setHeartbeatFreq(30 * 1000) //心跳包，30秒一次
                .setSocketAddress(new SocketAddress(socketAddress, port))
                // 定义消息协议，方便解决 socket黏包、分包的问题，如果客户端定义了消息协议，那么
                // 服务端也要对应对应的消息协议，如果这里没有定义消息协议，服务端也不需要定义
//                .setReaderProtocol(new DefaultMessageProtocol())
                .setReconnectionManager(null)//不重连
                .build();
        // 初始化
        EasySocket.getInstance().createSpecifyConnection(options, context);// 创建一个socket连接
    }

    /**
     * 发送授权信息
     *
     * @param basedata
     */
    @SuppressLint("NewApi")
    public static void sendAuthorizeMsg(String basedata, String address) {
        try {
            byte[] send = new byte[0];
            send = Base64.getMimeDecoder().decode(basedata);
            byte[] sendlen = new byte[4];
            int len = send.length;

            for (int i = 0; i < sendlen.length; i++) {
                int move = 8 * i;
                sendlen[i] = (byte) ((len >> move) & 0xff);
            }
            EasySocket.getInstance().upMessage(sendlen, address);
            EasySocket.getInstance().upMessage(send, address);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //关闭连接
    public static void closeConnection(String socketAddress, int port, boolean needReconnect) {
        EasySocket.getInstance().disconnect(socketAddress + ":" + port, false);
    }

}
